// 菜单切换功能
const menuItems = document.querySelectorAll('.menu-item');
const submenuItems = document.querySelectorAll('.submenu-item');
const currentMenuTitle = document.querySelector('#current-menu .title');
const dataList = document.getElementById('data-list');
const dataListDonation = document.getElementById('data-list-donation');

// 档案捐赠分页相关元素
const prevPageBtnDonation = document.getElementById('prev-page-donation');
const nextPageBtnDonation = document.getElementById('next-page-donation');
const pageInfoDonation = document.getElementById('page-info-donation');
const pageInputDonation = document.getElementById('page-input-donation');
const pageSizeSelectDonation = document.getElementById('page-size-donation');

// 档案捐赠分页状态
let currentPageDonation = 1;
let pageSizeDonation = 10;
let totalPagesDonation = 20;

// 轮播图功能
let currentSlide = 0;
const slides = document.querySelectorAll('.carousel-slide');
const indicators = document.querySelectorAll('.indicator');

function showSlide(index) {
    // 隐藏所有幻灯片
    slides.forEach(slide => slide.classList.remove('active'));
    // 显示指定幻灯片
    slides[index].classList.add('active');

    // 更新指示器
    indicators.forEach(indicator => indicator.classList.remove('active'));
    indicators[index].classList.add('active');

    currentSlide = index;
}

function nextSlide() {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide(currentSlide);
}

// 自动播放
let slideInterval = setInterval(nextSlide, 3000);

// 指示器点击事件
indicators.forEach((indicator, index) => {
    indicator.addEventListener('click', () => {
        clearInterval(slideInterval);
        showSlide(index);
        slideInterval = setInterval(nextSlide, 3000);
    });
});

// 初始化显示第一张幻灯片
showSlide(currentSlide);

// submenu 显示控制
let activeSubmenu = null;

// 树形菜单功能
const treeItems = document.querySelectorAll('.tree-item');
const treeTexts = document.querySelectorAll('.tree-text');

// 分页功能
const prevPageBtn = document.getElementById('prev-page');
const nextPageBtn = document.getElementById('next-page');
const pageInfo = document.getElementById('page-info');
const pageInput = document.getElementById('page-input');
const pageSizeSelect = document.getElementById('page-size'); // 添加页大小选择元素

// 当前状态
let currentPage = 1;
let pageSize = 10; // 默认页大小为10
let searchKeyword = ''; // 搜索关键词
let searchType = 'all'; // 搜索类型
let totalPages = 30; // 初始化为30页（300条数据每页10条）

// 模拟数据生成
function generateMockData() {
    const types = ['文书档案', '科技档案', '专门档案', '声像档案', '电子档案'];
    const periods = ['1950-1960', '1960-1970', '1970-1980', '1980-1990', '1990-2000', '2000-2010', '2010-2020'];
    const retentionPeriods = ['永久', '长期', '短期'];
    const mockData = [];

    // 生成300条模拟数据
    for (let i = 1; i <= 300; i++) {
        const randomType = types[Math.floor(Math.random() * types.length)];
        const randomPeriod = periods[Math.floor(Math.random() * periods.length)];
        const randomRetention = retentionPeriods[Math.floor(Math.random() * retentionPeriods.length)];

        mockData.push({
            id: i,
            title: `朝阳区${randomType}${i}——${randomPeriod}年${i % 12 + 1}月记录材料`,
            type: randomType,
            period: randomPeriod,
            quantity: Math.floor(Math.random() * 100) + 1,
            documentNumber: `朝档${i}号`,
            retentionPeriod: randomRetention,
            description: `${randomPeriod}年间${randomType}的重要记录，包含${Math.floor(Math.random() * 50) + 10}份文件资料。`
        });
    }

    return mockData;
}

// 生成档案捐赠模拟数据
function generateDonationMockData() {
    const types = ['文书档案', '科技档案', '专门档案', '声像档案', '电子档案'];
    const periods = ['1950-1960', '1960-1970', '1970-1980', '1980-1990', '1990-2000', '2000-2010', '2010-2020'];
    const donors = ['张先生', '李女士', '王先生', '赵女士', '陈先生', '刘女士', '杨先生', '黄女士'];
    const mockData = [];

    // 生成200条模拟数据
    for (let i = 1; i <= 200; i++) {
        const randomType = types[Math.floor(Math.random() * types.length)];
        const randomPeriod = periods[Math.floor(Math.random() * periods.length)];
        const randomDonor = donors[Math.floor(Math.random() * donors.length)];
        const randomYear = Math.floor(Math.random() * (2023 - 2010)) + 2010;
        const randomMonth = Math.floor(Math.random() * 12) + 1;

        mockData.push({
            id: i,
            title: `朝阳区${randomType}捐赠项目${i}`,
            type: randomType,
            period: randomPeriod,
            donor: randomDonor,
            donateDate: `${randomYear}-${randomMonth.toString().padStart(2, '0')}`,
            description: `${randomDonor}于${randomYear}年${randomMonth}月捐赠的${randomType}，包含${Math.floor(Math.random() * 30) + 5}份文件资料。`
        });
    }

    return mockData;
}

// 搜索功能
function searchData(data) {
    if (!searchKeyword.trim()) {
        return data; // 如果搜索关键词为空，返回所有数据
    }

    return data.filter(item => {
        if (searchType === 'all') {
            return item.title.includes(searchKeyword) ||
                item.type.includes(searchKeyword) ||
                item.period.includes(searchKeyword);
        } else if (searchType === 'title') {
            return item.title.includes(searchKeyword);
        } else if (searchType === 'type') {
            return item.type.includes(searchKeyword);
        } else if (searchType === 'year') {
            return item.period.includes(searchKeyword);
        }
        return false;
    });
}

// 获取当前需要显示的数据
function getCurrentData(data) {
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    return data.slice(start, end);
}

// 初始化
function init() {
    // 更新总页数
    function updateTotalPages() {
        const data = generateMockData();
        const searchResult = searchData(data);
        totalPages = Math.ceil(searchResult.length / pageSize);
        // 确保当前页不超过总页数
        if (currentPage > totalPages && totalPages > 0) {
            currentPage = totalPages;
        }
    }

    // 页大小变更事件
    pageSizeSelect.addEventListener('change', () => {
        pageSize = parseInt(pageSizeSelect.value);
        currentPage = 1; // 重置到第一页
        updateTotalPages();
        updateList();
        updatePagination();
    });

    // 档案捐赠页大小变更事件
    if (pageSizeSelectDonation) {
        pageSizeSelectDonation.addEventListener('change', () => {
            pageSizeDonation = parseInt(pageSizeSelectDonation.value);
            currentPageDonation = 1; // 重置到第一页
            updateList();
        });
    }

    // 页码输入框事件
    pageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            const page = parseInt(pageInput.value);
            if (page >= 1 && page <= totalPages) {
                goToPage(page);
            } else {
                alert('请输入有效的页码');
                pageInput.value = currentPage;
            }
        }
    });

    // 档案捐赠页码输入框事件
    if (pageInputDonation) {
        pageInputDonation.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const page = parseInt(pageInputDonation.value);
                if (page >= 1 && page <= totalPagesDonation) {
                    goToDonationPage(page);
                } else {
                    alert('请输入有效的页码');
                    pageInputDonation.value = currentPageDonation;
                }
            }
        });

        pageInputDonation.addEventListener('blur', () => {
            const page = parseInt(pageInputDonation.value);
            if (page >= 1 && page <= totalPagesDonation) {
                goToDonationPage(page);
            } else {
                pageInputDonation.value = currentPageDonation;
            }
        });
    }

    // 页码输入框失焦事件
    pageInput.addEventListener('blur', () => {
        const page = parseInt(pageInput.value);
        if (page >= 1 && page <= totalPages) {
            goToPage(page);
        } else {
            pageInput.value = currentPage;
        }
    });

    // 菜单点击事件
    menuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加当前点击项的激活状态
            this.classList.add('active');

            // 显示 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                // 隐藏之前激活的 submenu
                if (activeSubmenu && activeSubmenu !== submenu) {
                    activeSubmenu.style.display = 'none';
                }

                // 显示当前 submenu
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            } else {
                // 如果点击的菜单项没有 submenu，隐藏所有 submenu
                document.querySelectorAll('.submenu').forEach(sub => {
                    sub.style.display = 'none';
                });
                activeSubmenu = null;
            }



            // 更新列表数据
            updateList();
        });

        // 鼠标移入事件
        item.addEventListener('mouseenter', function () {
            // 隐藏所有已激活的 submenu
            if (activeSubmenu) {
                activeSubmenu.style.display = 'none';
                activeSubmenu = null;
            }

            // 显示当前菜单项的 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            }
        });

        // 鼠标移出事件
        item.addEventListener('mouseleave', function (e) {
            // 检查鼠标是否移向 submenu
            const submenu = this.querySelector('.submenu');
            if (submenu && activeSubmenu === submenu) {
                // 使用 setTimeout 来处理鼠标移出到 submenu 的情况
                setTimeout(() => {
                    if (!submenu.matches(':hover')) {
                        submenu.style.display = 'none';
                        if (activeSubmenu === submenu) {
                            activeSubmenu = null;
                        }
                    }
                }, 100);
            }
        });
    });

    // 二级菜单点击事件
    submenuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.stopPropagation(); // 阻止事件冒泡

            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加父级菜单项的激活状态
            this.closest('.menu-item').classList.add('active');

            // 更新当前菜单显示
            const submenuText = this.textContent;
            if (submenuText) {
                currentMenuTitle.textContent = submenuText;
            }
            const submenuType = this.dataset.submenu;
            let targetTreeType = '';

            // 页面跳转逻辑
            let targetUrl = '';
            if (submenuType === 'status1') {
                targetUrl = '../work-status/index.html?type=exhibition';
            } else if (submenuType === 'statu2') {
                targetUrl = '../work-status/index.html?type=inquiry';
            } else if (submenuType === 'service4') {
                targetUrl = '../public-service/index.html?type=exhibition';
            } else if (submenuType === 'service5') {
                targetUrl = '../public-service/index.html?type=inquiry';
            } else if (submenuType === 'service1') {
                targetUrl = '../public-service/index.html?type=reservation';
            } else if (submenuType === 'service2') {
                targetUrl = '../public-service/index.html?type=message';
            } else if (submenuType === 'service3') {
                targetUrl = '../public-service/index.html?type=donation';
            } else if (submenuType === 'overview1') {
                targetUrl = '../archival-collections/index.html?type=inquiry';
            } else if (submenuType === 'overview2') {
                targetUrl = '../archival-collections/index.html?type=exhibition';
            } else if (submenuType === 'culture1') {
                targetUrl = '../chronicle-culture/index.html?type=exhibition';
            } else if (submenuType === 'culture2') {
                targetUrl = '../chronicle-culture/index.html?type=inquiry';
            } else if (submenuType === 'culture3') {
                targetUrl = '../chronicle-culture/index.html?type=culture';
            }

            // 如果有目标URL，则跳转到对应页面
            if (targetUrl) {
                window.location.href = targetUrl;
                return;
            }

            // 获取各个内容区域
            //service4 查档指南
            const introContainer = document.querySelector('.intro-container')
            //service5开放档案
            const guideContainer = document.querySelector('.guide-container')
            //service1观展预约
            const donationContainer2 = document.querySelector('.list-content-container');
            //service2业务咨询
            const consultationContainer = document.querySelector('.consultation-message');
            //service3档案捐赠
            const reservationContainer = document.querySelector('.watch-reservation');
            // 根据树项类型显示对应的内容区域
            if (submenuType === 'service4') {
                introContainer.style.display = 'block';
                guideContainer.style.display = 'none'
                donationContainer2.style.display = 'none'
                consultationContainer.style.display = 'none';
                reservationContainer.style.display = 'none';
                targetTreeType = 'exhibition';
            } else if (submenuType === 'service5') {
                introContainer.style.display = 'none'
                donationContainer2.style.display = 'none';
                guideContainer.style.display = 'block'
                consultationContainer.style.display = 'none';
                reservationContainer.style.display = 'none';
                targetTreeType = 'inquiry';
            } else if (submenuType === 'service1') {
                introContainer.style.display = 'none'
                donationContainer2.style.display = 'block';
                guideContainer.style.display = 'none'
                consultationContainer.style.display = 'none';
                reservationContainer.style.display = 'none';
                targetTreeType = 'reservation';
            } else if (submenuType === 'service2') {
                introContainer.style.display = 'none'
                donationContainer2.style.display = 'none';
                guideContainer.style.display = 'none'
                consultationContainer.style.display = 'block';
                reservationContainer.style.display = 'none';
                targetTreeType = 'message';
            } else if (submenuType === 'service3') {
                introContainer.style.display = 'none'
                donationContainer2.style.display = 'none';
                guideContainer.style.display = 'none'
                consultationContainer.style.display = 'none';
                reservationContainer.style.display = 'block';
                targetTreeType = 'donation';
            } else {
                introContainer.style.display = 'block';
                guideContainer.style.display = 'none'
                donationContainer2.style.display = 'none'
                consultationContainer.style.display = 'none';
                reservationContainer.style.display = 'none';
                targetTreeType = 'exhibition';
            }
            const targetTreeItem = document.querySelector(`.tree-item[data-tree="${targetTreeType}"]`);
            if (submenuType && targetTreeItem) {
                // 移除所有树项的选中状态
                treeItems.forEach(i => i.classList.remove('selected'));
                // 添加目标树项的选中状态
                targetTreeItem.classList.add('selected');
            }
            // 更新列表数据
            updateList();
        });
    });

    // 表单提交处理
    const consultationForm = document.getElementById('consultation-form');
    if (consultationForm) {
        consultationForm.addEventListener('submit', function (e) {
            e.preventDefault();
            // 模拟表单提交
            alert('业务咨询已提交，我们会尽快回复您！');
            consultationForm.reset();
        });
    }

    const reservationForm = document.getElementById('reservation-form');
    if (reservationForm) {
        reservationForm.addEventListener('submit', function (e) {
            e.preventDefault();
            // 模拟表单提交
            alert('观展预约已提交成功！');
            reservationForm.reset();
        });
    }

    // 验证码刷新功能
    const captchaImg = document.getElementById('captcha-img');
    if (captchaImg) {
        captchaImg.addEventListener('click', function () {
            // 模拟刷新验证码
            this.src = '../assets/captcha.png?t=' + new Date().getTime();
        });
    }

    const reservationCaptchaImg = document.getElementById('reservation-captcha-img');
    if (reservationCaptchaImg) {
        reservationCaptchaImg.addEventListener('click', function () {
            // 模拟刷新验证码
            this.src = '../assets/captcha.png?t=' + new Date().getTime();
        });
    }

    // 树形菜单点击事件
    treeTexts.forEach(item => {
        item.addEventListener('click', function () {
            // 移除所有树项的选中状态
            treeItems.forEach(i => i.classList.remove('selected'));
            // 添加当前点击项的选中状态
            this.parentElement.classList.add('selected');

            // 更新当前菜单显示
            const treeText = this.textContent;
            if (treeText) {
                currentMenuTitle.textContent = treeText;
            }

            // 获取当前点击的树项类型
            const treeType = this.parentElement.getAttribute('data-tree');

            // 获取各个内容区域
            const introContainer = document.querySelector('.intro-container');
            const donationContainer = document.querySelector('.list-content-container');
            const consultationContainer = document.querySelector('.consultation-message');
            const reservationContainer = document.querySelector('.watch-reservation');
            const guideContainer = document.querySelector('.guide-container');

            // 默认隐藏所有容器
            if (introContainer) introContainer.style.display = 'none';
            if (donationContainer) donationContainer.style.display = 'none';
            if (consultationContainer) consultationContainer.style.display = 'none';
            if (reservationContainer) reservationContainer.style.display = 'none';
            if (guideContainer) guideContainer.style.display = 'none';

            // 根据树项类型显示对应的内容区域
            if (treeType === 'inquiry') { // 开放档案
                if (introContainer) introContainer.style.display = 'block';
            } else if (treeType === 'donation') { // 档案捐赠
                if (donationContainer) donationContainer.style.display = 'block';
            } else if (treeType === 'message') { // 业务咨询
                if (consultationContainer) consultationContainer.style.display = 'block';
            } else if (treeType === 'reservation') { // 观展预约
                if (reservationContainer) reservationContainer.style.display = 'block';
            } else if (treeType === 'exhibition') { // 查档指南
                if (guideContainer) guideContainer.style.display = 'block';
            } else {
                // 默认显示查档指南
                if (guideContainer) guideContainer.style.display = 'block';
            }

            // 更新列表数据
            updateList();
        });
    });

    // 获取搜索相关元素
    const searchInput = document.getElementById('search-input');
    const searchTypeSelect = document.getElementById('search-type');
    const searchBtn = document.getElementById('search-btn');

    // 搜索按钮点击事件
    searchBtn.addEventListener('click', () => {
        performSearch();
    });

    // 回车键搜索
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            performSearch();
        }
    });

    // 搜索类型变更事件
    searchTypeSelect.addEventListener('change', () => {
        searchType = searchTypeSelect.value;
    });

    // 执行搜索
    function performSearch() {
        searchKeyword = searchInput.value.trim();
        searchType = searchTypeSelect.value;
        currentPage = 1; // 搜索后重置到第一页
        updateList();
        updatePagination();
    }

    // 分页功能
    prevPageBtn.addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            updateList();
            updatePagination();
        }
    });

    nextPageBtn.addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            updateList();
            updatePagination();
        }
    });

    // 档案捐赠分页功能
    if (prevPageBtnDonation) {
        prevPageBtnDonation.addEventListener('click', () => {
            if (currentPageDonation > 1) {
                currentPageDonation--;
                renderDonationListData();
                updateDonationPagination();
            }
        });
    }

    if (nextPageBtnDonation) {
        nextPageBtnDonation.addEventListener('click', () => {
            if (currentPageDonation < totalPagesDonation) {
                currentPageDonation++;
                renderDonationListData();
                updateDonationPagination();
            }
        });
    }

    // 初始化列表
    updateList();
    updatePagination();

    // 如果当前显示的是档案捐赠区域，初始化数据
    const donationContainer3 = document.querySelector('.list-content-container');
    if (donationContainer3 && donationContainer3.style.display !== 'none') {
        renderDonationListData();
        updateDonationPagination();
    }

    // 初始化显示：根据默认选中的tree-item显示对应的容器
    const introContainer = document.querySelector('.intro-container');
    const donationContainer4 = document.querySelector('.list-content-container');
    const consultationContainer = document.querySelector('.consultation-message');
    const reservationContainer = document.querySelector('.watch-reservation');
    const guideContainer = document.querySelector('.guide-container');

    // 默认隐藏所有容器
    if (introContainer) introContainer.style.display = 'none';
    if (donationContainer4) donationContainer4.style.display = 'none';
    if (consultationContainer) consultationContainer.style.display = 'none';
    if (reservationContainer) reservationContainer.style.display = 'none';
    if (guideContainer) guideContainer.style.display = 'none';

    // 获取默认选中的tree-item
    const defaultSelectedTreeItem = document.querySelector('.tree-item.selected');
    if (defaultSelectedTreeItem) {
        const defaultTreeType = defaultSelectedTreeItem.dataset.tree;

        // 根据默认选中的tree-item显示对应的容器
        if (defaultTreeType === 'inquiry') { // 开放档案
            if (introContainer) introContainer.style.display = 'block';
        } else if (defaultTreeType === 'donation') { // 档案捐赠
            if (donationContainer4) donationContainer4.style.display = 'block';
        } else if (defaultTreeType === 'message') { // 业务咨询
            if (consultationContainer) consultationContainer.style.display = 'block';
        } else if (defaultTreeType === 'reservation') { // 观展预约
            if (reservationContainer) reservationContainer.style.display = 'block';
        } else if (defaultTreeType === 'exhibition') { // 查档指南
            if (guideContainer) guideContainer.style.display = 'block';
        }
    } else {
        // 如果没有默认选中的tree-item，则默认显示查档指南
        if (guideContainer) guideContainer.style.display = 'block';
    }

}

// 更新列表内容
function updateList() {
    // 获取各容器元素
    const introContainer = document.querySelector('.intro-container');
    const donationContainer = document.querySelector('.list-content-container');

    const isIntroVisible = introContainer && introContainer.style.display !== 'none';
    const isDonationVisible = donationContainer && donationContainer.style.display !== 'none';

    if (isIntroVisible) {
        // 如果intro-container可见，则渲染表格数据
        renderTableData();
    } else if (isDonationVisible) {
        // 如果list-content-container可见，则渲染档案捐赠列表数据
        renderDonationListData();
        updateDonationPagination();
    } else {
        // 否则保持原有逻辑，渲染列表数据
        renderListData();
    }
}

// 渲染档案捐赠列表数据
function renderDonationListData() {
    // 清空列表内容
    if (dataListDonation) {
        dataListDonation.innerHTML = '';
    }

    // 模拟数据列表
    const data = generateDonationMockData();

    // 获取当前页数据
    const start = (currentPageDonation - 1) * pageSizeDonation;
    const end = start + pageSizeDonation;
    const currentData = data.slice(start, end);

    // 创建列表项并添加到列表中
    if (dataListDonation) {
        currentData.forEach(item => {
            const li = document.createElement('li');
            li.className = 'list-item';
            li.innerHTML = `
                
                <div class="item-donor">
                    <span>捐赠人：宋庆龄致王安娜书信档案入藏中央档案馆宋庆龄致王安娜书信档案入藏中央档案馆……</span>
                    <span>2024-12-03</span>
                    </div>
            `;
            dataListDonation.appendChild(li);
        });
    }
}

function renderTableData() {
    // 清空数据列表
    dataList.innerHTML = '';

    // 模拟数据列表
    const data = generateMockData();

    // 搜索数据
    const searchResult = searchData(data);

    // 获取当前页数据
    const currentData = getCurrentData(searchResult);

    // 添加表格行数据
    currentData.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.title}</td>
            <td>${item.type}</td>
            <td>${item.period}</td>
            <td>${item.quantity}</td>
            <td>${item.documentNumber}</td>
            <td>${item.retentionPeriod}</td>
            <td><button class="view-btn">查看</button></td>
        `;
        dataList.appendChild(row);
    });
}

function renderListData() {
    // 清空列表内容
    dataList.innerHTML = '';

    // 模拟数据列表
    const data = generateMockData();

    // 搜索数据
    const searchResult = searchData(data);

    // 获取当前页数据
    const currentData = getCurrentData(searchResult);

    // 创建列表项并添加到列表中
    currentData.forEach(item => {
        const li = document.createElement('li');
        li.className = 'list-item';
        li.innerHTML = `
            <div class="item-header">
                <h3>${item.title}</h3>
                <span class="item-type">${item.type}</span>
            </div>
            <div class="item-period">${item.period}</div>
            <div class="item-description">${item.description}</div>
        `;
        dataList.appendChild(li);
    });
}

// 更新分页信息
function updatePagination() {
    // 计算总页数
    const data = generateMockData();
    const searchResult = searchData(data);
    totalPages = Math.ceil(searchResult.length / pageSize);

    // 确保当前页不超过总页数
    if (currentPage > totalPages && totalPages > 0) {
        currentPage = totalPages;
        updateList();
    }

    // 更新页码显示
    let pageNumbers = '';

    // 始终显示第一页
    if (currentPage === 1) {
        pageNumbers += '<span class="current page-item">1</span>';
    } else {
        pageNumbers += '<span class="page-item" onclick="goToPage(1)">1</span>';
    }

    // 如果当前页大于4，显示省略号
    if (currentPage > 4) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 显示当前页前后各两页
    let start = Math.max(2, currentPage - 2);
    let end = Math.min(totalPages - 1, currentPage + 2);

    for (let i = start; i <= end; i++) {
        if (i === currentPage) {
            pageNumbers += `<span class="current page-item">${i}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToPage(${i})">${i}</span>`;
        }
    }

    // 如果当前页小于总页数-3，显示省略号
    if (currentPage < totalPages - 3) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 始终显示最后一页
    if (totalPages > 1) {
        if (currentPage === totalPages) {
            pageNumbers += `<span class="current page-item">${totalPages}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToPage(${totalPages})">${totalPages}</span>`;
        }
    }

    pageInfo.innerHTML = pageNumbers;

    // 更新按钮状态
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages;

    // 更新页码输入框
    pageInput.value = currentPage;
}

// 更新档案捐赠分页信息
function updateDonationPagination() {
    // 计算总页数
    const data = generateDonationMockData();
    totalPagesDonation = Math.ceil(data.length / pageSizeDonation);

    // 确保当前页不超过总页数
    if (currentPageDonation > totalPagesDonation && totalPagesDonation > 0) {
        currentPageDonation = totalPagesDonation;
        renderDonationListData();
    }

    // 更新页码显示
    let pageNumbers = '';

    // 始终显示第一页
    if (currentPageDonation === 1) {
        pageNumbers += '<span class="current page-item">1</span>';
    } else {
        pageNumbers += '<span class="page-item" onclick="goToDonationPage(1)">1</span>';
    }

    // 如果当前页大于4，显示省略号
    if (currentPageDonation > 4) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 显示当前页前后各两页
    let start = Math.max(2, currentPageDonation - 2);
    let end = Math.min(totalPagesDonation - 1, currentPageDonation + 2);

    for (let i = start; i <= end; i++) {
        if (i === currentPageDonation) {
            pageNumbers += `<span class="current page-item">${i}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToDonationPage(${i})">${i}</span>`;
        }
    }

    // 如果当前页小于总页数-3，显示省略号
    if (currentPageDonation < totalPagesDonation - 3) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 始终显示最后一页
    if (totalPagesDonation > 1) {
        if (currentPageDonation === totalPagesDonation) {
            pageNumbers += `<span class="current page-item">${totalPagesDonation}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToDonationPage(${totalPagesDonation})">${totalPagesDonation}</span>`;
        }
    }

    if (pageInfoDonation) {
        pageInfoDonation.innerHTML = pageNumbers;
    }

    // 更新按钮状态
    if (prevPageBtnDonation) prevPageBtnDonation.disabled = currentPageDonation === 1;
    if (nextPageBtnDonation) nextPageBtnDonation.disabled = currentPageDonation === totalPagesDonation;

    // 更新页码输入框
    if (pageInputDonation) pageInputDonation.value = currentPageDonation;
}

// 跳转到指定页码的函数
function goToPage(page) {
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        updateList();
        updatePagination();
    }
}

// 跳转到档案捐赠指定页码的函数
function goToDonationPage(page) {
    if (page >= 1 && page <= totalPagesDonation) {
        currentPageDonation = page;
        renderDonationListData();
        updateDonationPagination();
    }
}

// 点击页面其他地方隐藏 submenu
function hideSubmenuOnClickOutside(e) {
    if (activeSubmenu && !activeSubmenu.contains(e.target) && !e.target.closest('.has-submenu')) {
        activeSubmenu.style.display = 'none';
        activeSubmenu = null;
    }
}

document.addEventListener('click', hideSubmenuOnClickOutside);

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 解析URL参数，根据type参数设置对应的树形菜单选中状态
    const urlParams = new URLSearchParams(window.location.search);
    const contentType = urlParams.get('type');

    if (contentType) {
        // 查找对应的树形菜单项
        const targetTreeItem = document.querySelector(`.tree-item[data-tree="${contentType}"]`);
        if (targetTreeItem) {
            // 移除所有树项的选中状态
            treeItems.forEach(item => item.classList.remove('selected'));
            // 添加目标树项的选中状态
            targetTreeItem.classList.add('selected');
            // 更新当前菜单标题
            const menuTitle = targetTreeItem.textContent.trim();
            if (menuTitle && currentMenuTitle) {
                currentMenuTitle.textContent = menuTitle;
            }
            // 获取当前点击的树项类型
            const treeType = targetTreeItem.getAttribute('data-tree');

            // 获取各个内容区域
            const introContainer = document.querySelector('.intro-container');
            const donationContainer = document.querySelector('.list-content-container');
            const consultationContainer = document.querySelector('.consultation-message');
            const reservationContainer = document.querySelector('.watch-reservation');
            const guideContainer = document.querySelector('.guide-container');

            // 默认隐藏所有容器
            if (introContainer) introContainer.style.display = 'none';
            if (donationContainer) donationContainer.style.display = 'none';
            if (consultationContainer) consultationContainer.style.display = 'none';
            if (reservationContainer) reservationContainer.style.display = 'none';
            if (guideContainer) guideContainer.style.display = 'none';

            // 根据树项类型显示对应的内容区域
            if (treeType === 'inquiry') { // 开放档案
                if (introContainer) introContainer.style.display = 'block';
            } else if (treeType === 'donation') { // 档案捐赠
                if (donationContainer) donationContainer.style.display = 'block';
            } else if (treeType === 'message') { // 业务咨询
                if (consultationContainer) consultationContainer.style.display = 'block';
            } else if (treeType === 'reservation') { // 观展预约
                if (reservationContainer) reservationContainer.style.display = 'block';
            } else if (treeType === 'exhibition') { // 查档指南
                if (guideContainer) guideContainer.style.display = 'block';
            } else {
                // 默认显示查档指南
                if (guideContainer) guideContainer.style.display = 'block';
            }

            // 更新列表数据
            updateList();
        }
    }

    // 初始化页面
    init();
});